package demo.json.servlet;

import demo.json.entity.Book;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import net.sf.json.JSONArray;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;


@WebServlet(name = "ServletJson", value = "/ServletJson")
public class ServletJson extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Book> Books = new ArrayList<Book>();
        Book b = new Book();
        b.setName("java基础");
        b.setAuther("张三");
        b.setPrice(78.20);
        Books.add(b);

        Book b1 = new Book();
        b1.setName("java进阶");
        b1.setAuther("李四");
        b1.setPrice(68.20);
        Books.add(b1);

        // 创建JSONArray对象
        JSONArray jsonArray = JSONArray.fromObject(Books);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print(jsonArray);
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
